import { _decorator, Component, find, instantiate, macro, Node, Prefab, UITransform, Vec3 } from 'cc';
import { Plant } from './Plant';
import { PeaBullet } from './PeaBullet';
import { AudioManager } from './manager/AudioManager';
import { Config } from './manager/Config';
const { ccclass, property } = _decorator;

@ccclass('PeaShooter')
export class PeaShooter extends Plant {
    @property(Number)
    shootDuration: number = 2;
    private shootTimer: number = 0;
    @property(Node)
    shootPointTransform: Node =null;
    @property(Prefab)
    peaBulletPrefab:Prefab=null;

    @property(Number)
    bulletSpeed:number=300;
    @property(Number)
    atk:number=20;
    update(dt: number): void {
        super.update(dt);
        this.shootTimer += dt;
    }
    enableUpdate(): void {
        super.enableUpdate();
        if(this.shootTimer >= this.shootDuration){
            this.shoot();
            this.shootTimer = 0;
        }
    }

    shoot(){
        // 实例化豌豆子弹
        let peaBullet= instantiate(this.peaBulletPrefab);
        AudioManager.Instance.playClip(Config.shoot,2);
        // 将豌豆子弹的父节点设置为 "Canvas/ForeGround/PeaBulletGroup"
        peaBullet.parent=find("Canvas/ForeGround/PeaBulletGroup");
        peaBullet.getComponent(PeaBullet).setSpeed(this.bulletSpeed);
        peaBullet.getComponent(PeaBullet).setAtk(this.atk);
        // 获取射击点在世界坐标系下的位置
        let shootPointWorldPos = this.shootPointTransform.getComponent(UITransform).convertToWorldSpaceAR(new Vec3(0, 0, 0));
        // 将射击点在世界坐标系下的位置转换为节点坐标系下的位置
        let targetLocalPos=this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(shootPointWorldPos);
        // 设置豌豆子弹的位置为节点坐标系下的目标位置
        peaBullet.setPosition(targetLocalPos);
    }
}


